﻿using System;
using System.Collections.Generic;
using wojilu.Apps.Qycms.Domain;
using wojilu.Apps.Qycms.Helper;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class SubjectController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public SubjectController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void SubjectList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var condition = " lng='" + DefaultLng + "'";
            DataPage<SubjectList> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var mid = ctx.GetInt("mid");
            set("mid", mid);
            if (mid > 0)
            {
                condition += " and mid = " + mid;
            }
            Int32 isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1 ";
                    break;

                case 2:
                    condition += " and isclass = 0 ";
                    break;
            }
            Int32 purview = ctx.GetInt("purview");
            if (purview > 0)
            {
                condition += " and purview = " + purview;
            }
            Int32 ismenu = ctx.GetInt("ismenu");
            switch (ismenu)
            {
                case 1:
                    condition += " and ismenu = 1 ";
                    break;

                case 2:
                    condition += " and ismenu = 0 ";
                    break;
            }
            Int32 iswap = ctx.GetInt("ismenu");
            switch (iswap)
            {
                case 1:
                    condition += " and iswap = 1 ";
                    break;

                case 2:
                    condition += " and iswap = 0 ";
                    break;
            }
            Int32 ishtml = ctx.GetInt("ishtml");
            switch (ishtml)
            {
                case 1:
                    condition += " and ishtml = 1 ";
                    break;

                case 2:
                    condition += " and ishtml = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = wojilu.Apps.Qycms.Domain.SubjectList.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void SubjectAdd()
        {
            SetPublic();
            setpublic();
            target(SubjectAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            var lng = DefaultLng;
            set("lng", lng);
            set("tab", ctx.Get("tab"));
            set("refalse", 1);
            var mlist = Model.find(" issid = 1").list();
            bind("modelarray", mlist);
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
            var tempname = cdb.findById<TempName>(1);
            bind("tempname", tempname);
            bind("filetemplate", cdb.findAll<TypeUrl>());
        }

        [HttpPost]
        public virtual void CheckDirName()
        {
            var dirname = ctx.Get("dirname");
            if (CheckDirName(dirname))
            {
                ctx.web.ResponseWrite("true");
            }
            else
            {
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [NonVisit]
        public string CDirName(String dirname)
        {
            var newDirName = dirname;
            CDirName(dirname, newDirName, 1);
            return newDirName;
        }

        [NonVisit]
        public void CDirName(String dirname, String newDirName, Int64 n)
        {
            if (CheckDirName(newDirName)) return;
            newDirName = dirname + n;
            CDirName(dirname, newDirName, n + 1);
        }

        [HttpPost]
        public virtual void SubjectAddDo()
        {
            wojilu.Apps.Qycms.Domain.SubjectList sj = new SubjectList();
            sj.pid = 50;
            sj.mid = ctx.PostInt("mid");
            sj.lng = ctx.Post("lng");
            sj.subjectname = ctx.Post("subjectname");
            sj.keywords = ctx.Post("keywords");
            sj.description = ctx.Post("description");
            sj.content = ctx.Post("content");
            sj.subpic = ctx.Post("subpic");
            var dirname = ctx.Post("dirname");
            var isdirname = ctx.PostInt("isdirname");
            if (isdirname == 1)
            {
                dirname = CHSPinYin.Convert(ctx.Post("subjectname"));
                sj.dirname = CDirName(dirname);
                sj.dirpath = CDirName(dirname);
            }
            else
            {
                sj.dirname = dirname;
                sj.dirpath = dirname;
            }
            var purview = ctx.PostInt("purview");
            sj.purview = purview;
            sj.isclass = 1;
            sj.styleid = ctx.PostInt("styleid");
            sj.ishtml = ctx.PostInt("ishtml");
            sj.iswap = ctx.PostInt("iswap");
            sj.waptempalte = ctx.Post("waptempalte");
            sj.indextemplates = ctx.Post("indextemplates");
            sj.template = ctx.Post("template");
            sj.filenamestyle = ctx.Post("filenamestyle");
            sj.pagemax = ctx.PostInt("pagemax");
            sj.addtime = DateTime.Now;
            Result result = sj.insert();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_add_log") + lang("log_extra_ok"), "{Id:" + sj.Id + ", Name:'" + sj.subjectname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void SubjectEdit(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(SubjectEditDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("type", "edit");
            var lng = DefaultLng;
            set("lng", lng);
            var subread = wojilu.Apps.Qycms.Domain.SubjectList.findById(Id);
            set("subread", subread);
            Configs config = Configs.find("valname=:v").set("v", "file_htmldir").first();
            set("file_htmldir", config.value);
            config = Configs.find("valname=:v").set("v", "is_alonelng").first();
            set("is_alonelng", config.value);
            var c1 = Configs.find("valname=:v").set("v", "domain").first();
            set("adminurl", c1.value);
            bind("filetemplate", cdb.findAll<TypeUrl>());
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
        }

        [HttpPost]
        public virtual void SubjectEditDo(Int64 Id)
        {
            wojilu.Apps.Qycms.Domain.SubjectList sj = wojilu.Apps.Qycms.Domain.SubjectList.findById(Id);
            sj.subjectname = ctx.Post("subjectname");
            sj.keywords = ctx.Post("keywords");
            sj.description = ctx.Post("description");
            sj.content = ctx.Post("content");
            sj.subpic = ctx.Post("subpic");
            var purview = ctx.PostInt("purview");
            sj.purview = purview;
            sj.styleid = ctx.PostInt("styleid");
            sj.ishtml = ctx.PostInt("ishtml");
            sj.iswap = ctx.PostInt("iswap");
            sj.waptempalte = ctx.Post("waptempalte");
            sj.indextemplates = ctx.Post("indextemplates");
            sj.template = ctx.Post("template");
            sj.filenamestyle = ctx.Post("filenamestyle");
            sj.pagemax = ctx.PostInt("pagemax");
            Result result = sj.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_edit_log") + lang("log_extra_ok"), "{Id:" + sj.Id + ", Name:'" + sj.subjectname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void SubSort()
        {
            var infoid = ctx.PostIdList("infoid");
            var pid = ctx.PostIdList("pid");
            var strArray = infoid.Split(new char[] { ',' });
            var strArray1 = pid.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                string condition = string.Format("Id = {0}", strArray[i]);
                db.updateBatch<Advert>("set pid=" + strArray1[i], condition);
            }
            logService.Add((User)ctx.viewer.obj, lang("subjectmanage_log_sort") + lang("log_extra_ok"), "{Id:" + infoid + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void SubSetting()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<SubjectList>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_log_istype") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_log_istype") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void SubDel(Int64 Id)
        {
            var num = db.delete<SubjectList>(Id);
            if (num > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_del_log") + lang("log_extra_ok"), "{Id:" + Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("subjectmanage_del_log") + lang("log_extra_no"), "{Id:" + Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
        }

        public bool CheckDirName(string dirname)
        {
            var modelSubjectList = wojilu.Apps.Qycms.Domain.SubjectList.find(" dirname =:d").set("d", dirname).first();
            if (modelSubjectList != null)
            {
                return false;
            }
            var modelTypeList = TypeList.find("dirpath=:d").set("d", dirname).first();
            return modelTypeList == null;
        }

    }
}
